import { ArgumentsHost, ExceptionFilter, HttpException, HttpStatus } from '@nestjs/common';
import { Request, Response } from 'express';

/** 全局异常过滤器 自动捕获 HttpException 和 HeepException 子类的异常 */
export class AllExceptionFilter implements ExceptionFilter {
  catch(exception: any, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const request = ctx.getRequest<Request>();
    const exceptionResponse = exception.getResponse?.();
    const status = exception instanceof HttpException ? exception.getStatus() : HttpStatus.INTERNAL_SERVER_ERROR;

    // 设置响应码
    response.status(status);
    // 返回响应体
    response.json({
      code: exception.code ?? status,
      error: exception.name,
      message: exceptionResponse?.message || exception.message,
      originalUrl: request.originalUrl,
    });
  }
}
